import { Body, Controller, FileTypeValidator, HttpException, MaxFileSizeValidator, ParseFilePipe, Post, UploadedFile, UploadedFiles, UseInterceptors } from '@nestjs/common';
import { AppService } from './app.service';
import { AnyFilesInterceptor, FileFieldsInterceptor, FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { storage } from './storage';
import { FileSizeValidationPipePipe } from './file-size-validation-pipe.pipe';


@Controller()
export class AppController {
  constructor(private readonly appService: AppService) { }

  //单文件上传
  @Post('aaa')
  //FileInterceptor内部就是对 multer api的封装
  @UseInterceptors(FileInterceptor('aaa', {
    dest: 'uploads'
  }))            
  //自定义管道限定最大上传字节(不推荐) @UploadedFile(FileSizeValidationPipePipe)
  uploadFile(@UploadedFile(
      //内置的Nest文件验证方法(推荐)
      new ParseFilePipe({
        exceptionFactory: (err) => {
          throw new HttpException(err, 404);
        },
        //TODO: 上传失败后如何及时清空数据?
        //validators也可以自定义,详情可以看通关秘籍23小节最后部分
        validators: [
            new MaxFileSizeValidator({maxSize: 100000 * 1024}),
            new FileTypeValidator({fileType:/^image\/(jpg|jpeg|png|gif)$/ })
        ],  
       }
    )) file: Express.Multer.File, @Body() body) {
    console.log('body', body);
    console.log('file', file);
  }


  //多文件上上传  File后面都多了个s
  @Post('bbb')
  @UseInterceptors(FilesInterceptor('bbb', 3, {
    dest: 'uploads'
  }))
  uploadFiles(@UploadedFiles() files: Array<Express.Multer.File>, @Body() body) {
    console.log('body', body);
    console.log('files', files);
  }


  //多文件字段
  @Post('ccc')
  @UseInterceptors(FileFieldsInterceptor(
    [
      { name: 'aaa', maxCount: 2 },
      { name: 'bbb', maxCount: 3 },
    ],
    {
      dest: 'uploads'
    }
  ))
  uploadFileFields(@UploadedFiles() files: { aaa?: Array<Express.Multer.File>, bbb?: Array<Express.Multer.File> }, @Body() body) {
    console.log('body', body);
    console.log('files', files);
  }


  //不知道哪些字段是file,可用Any
  @Post('ddd')
  @UseInterceptors(AnyFilesInterceptor({
      storage: storage
  }))
  uploadAnyFiles(@UploadedFiles() files: Array <Express.Multer.File>, @Body() body) {
      console.log('body', body);
      console.log('files', files);
  }

}
